import { createRouter, createWebHistory } from "vue-router";
import HomeView from "../views/HomeView.vue";
import { getToken, setToken, removeToken } from "@/utils/token";
import { userStore } from "@/stores/user";
import { getUserinfo } from "@/api/user";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      component: () => import("@/layout/index.vue"),
      redirect: "/dashboard",
      children: [
        {
          path: "/dashboard",
          name: "dashboard",
          component:  () => import("@/views/DashboardView.vue"),
          meta: {
            title: "数据面板",
          },
        },
        {
          path: "/cate",
          name: "cate",
          component:  () => import("@/views/CategoryView.vue"),
          meta: {
            title: "分类管理",
          },
        },
        {
          path: "/admin",
          name: "admin",
          component:  () => import("@/views/AdminuserView.vue"),
          meta: {
            title: "管理员页面",
          },
        },
        {
          path: "/role",
          name: "role",
          component:  () => import("@/views/RoleView.vue"),
          meta: {
            title: "RoleView",
          },
        },
        {
          path: "/about",
          name: "about",
          // route level code-splitting
          // this generates a separate chunk (About.[hash].js) for this route
          // which is lazy-loaded when the route is visited.
          component: () => import("../views/AboutView.vue"),
          meta: {
            title: "about",
          },
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/LoginView.vue"),
      meta: {
        title: "用户登录",
      },
    },
    {
      path: "/:pathMatch(.*)*",
      name: "not-found",
      component: () => import("@/views/NotFoundView.vue"),
      meta: {
        title: "页面不存在",
      },
    },
  ],
});

const pageTitle = "内容管理系统";
const whiteList = ["login", "not-found"];
router.beforeEach(async (to, from, next) => {
  // console.log("to: ", to);
  // console.log("from: ", from);
  if (to.meta.title) {
    document.title = to.meta.title + " - " + pageTitle;
  }

  const token = getToken();
  if (!token) {
    if (whiteList.indexOf(to.name) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
  } else {
    // token存在
    if (to.name == "login") {
      next("/");
    } else {
      // 读取用户信息
      // pinia
      const store = userStore();
      if (store.userName) {
        next();
      } else {
        let res = await getUserinfo();
        // console.log('res: ', res);
        if (res.code == 1) {
          setToken(res.data.token);
          store.setUserinfo(res.data);
          next();
        } else {
          removeToken();
          next(`/login?redirect=${to.path}`);
        }
      }
    }
  }

  // next();
});

export default router;
